package com.leetcode.offer.chapter2;

/**
 * @author Dennis Li
 * @date 2020/7/11 17:03
 */
public class findNumberIn2DArray_04 {
    public boolean findNumberIn2DArray(int[][] matrix, int target) {
        // 讲究版本
        // Arrays.stream(matrix).anyMatch(ints -> Arrays.stream(ints).anyMatch(value -> value == target));

        for (int[] ints : matrix) {
            int result = binarySearch(ints, target, 0, ints.length - 1);
            if (result != -1) return true;
        }
        return false;
    }

    public int binarySearch(int[] arr, int target, int lo, int hi) {
        if (lo > hi) return -1;
        int mid = (lo + hi) / 2;
        if (arr[mid] < target) return binarySearch(arr, target, mid + 1, hi);
        else if (arr[mid] > target) return binarySearch(arr, target, lo, mid - 1);
        else return mid;
    }
}
